package com.fintech.third.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.template.User;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerUtil {
	
	
	public static String creatHtmlFromModel(String filePath,String htmlFileName){
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String htmlFilePath=ThirdSystemUtil.class.getResource(thirdProperties.getImage_path()).getPath()+htmlFileName+".html";
		  BufferedInputStream in = null;
		           FileWriter out = null;
		           try {
		               //模板文件
		               File file = new File(filePath);
		              //构造输入流
		              in = new BufferedInputStream(new FileInputStream(file));
		              int len;
		              byte[] bytes = new byte[1024];
		              //模板内容
		              StringBuilder content = new StringBuilder();
		              while((len = in.read(bytes)) != -1) {
		                  content.append(new String(bytes, 0, len, "utf-8"));
		              }
		              //构造Configuration
		              Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
		              //构造StringTemplateLoader
		              StringTemplateLoader loader = new StringTemplateLoader();
		              //添加String模板
		              loader.putTemplate("test", content.toString());
		              //把StringTemplateLoader添加到Configuration中
		              configuration.setTemplateLoader(loader);
		              
		              //构造Model
		              User user = new User("小狗","小猫","小花","小牛","小草","小数");
		              //获取模板
		              Template template = configuration.getTemplate("test");
		              //构造输出路
		              out = new FileWriter(htmlFilePath);
		              //生成HTML
		              template.process(user, out);
		          } catch (Exception e) {
		              e.printStackTrace();
		          }  finally {
		              if(null != in) {
		                  try {
		                      in.close();
		                  } catch (IOException e) {
		                      e.printStackTrace();
		                  }
		              }
		              if(null != out) {
		                  try {
		                      out.close();
		                  } catch (IOException e) {
		                      e.printStackTrace();
		                  }
		              }
		          }
		          return htmlFilePath;
		
	}
}
